﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using System.IO;
using LitJson;
using DSEngine.Sprite;

namespace DSEngine.AnimationContentPiple
{
    [ContentProcessor(DisplayName = "DSEngine.AnimationContentPiple.AnimationProcessor")]
    public class AnimationProcessor : ContentProcessor<string, SpAnimationInfo>
    {
        public override SpAnimationInfo Process(string input, ContentProcessorContext context)
        {
            //SpAnimationInfo model = new SpAnimationInfo();

            //string[] tmp = input.Split(new string[] { "{|}" }, StringSplitOptions.None);
            //string file = tmp[0];
            //string path = System.IO.Path.GetDirectoryName(file);
            //string fileName = System.IO.Path.GetFileNameWithoutExtension(file);
            //string textureName = path + "\\" + fileName + "_texture.png";


            //// Load the sprite texture into memory.
            //ExternalReference<TextureContent> textureReference =
            //            new ExternalReference<TextureContent>(textureName);

            //TextureContent texture =
            //context.BuildAndLoadAsset<TextureContent,
            //                          TextureContent>(textureReference, "TextureProcessor");

            //BitmapContent bc = texture.Faces[0][0];


            //JsonData jData = LitJson.JsonMapper.ToObject(tmp[1]);
            //JsonData frames = jData["frames"];

            //Dictionary<string, Rectangle> dFrame = new Dictionary<string, Rectangle>(); ;
            //List<string> names = new List<string>();
            //for (int i = 0; i < frames.Count; i++)
            //{
            //    JsonData jcur = frames[i];
            //    Rectangle rect = new Rectangle();
            //    string fname = (jcur["name"].ToString());

            //    Vector2 tmpVector = Vector2.Zero;

            //    rect.X =(int)(bc.Width * float.Parse(jcur["offset"]["x"].ToString()));
            //    rect.Y = (int)(bc.Height * float.Parse(jcur["offset"]["y"].ToString()));

            //    rect.Width = (int)(bc.Width * float.Parse(jcur["size"]["x"].ToString()));
            //    rect.Height = (int)(bc.Height * float.Parse(jcur["size"]["y"].ToString()));

            //    dFrame.Add(fname, rect);

            //}
            //frames = jData["animations"];
            //frames = frames[0];

            //model.IsLoop = Boolean.Parse(frames["loops"].ToString()) ? 1 : 0;
            //model.Name = frames["name"].ToString();
            //model.IsSmooth = Boolean.Parse(frames["smooth"].ToString()) ? 1 : 0;

            //frames = frames["key_frames"];
            //Dictionary<string, float> dDuring = new Dictionary<string, float>(); ;
            //for (int i = 0; i < frames.Count; i++)
            //{
            //    JsonData jcur = frames[i];
            //    foreach (var item in dFrame)
            //    {
            //        if (jcur["frame"].ToString() == item.Key)
            //        {
            //            if (dDuring.ContainsKey(item.Key) == false)
            //            {
            //                dDuring.Add(item.Key, 1000 * float.Parse(jcur["duration"].ToString()));
            //            }
            //            else
            //            {
            //                model.FrameOrder.Add(item.Key);
            //            }
            //        }
            //    }
            //}
            //model.Frames = dFrame;
            //model.During = dDuring;
            //model.Texture = new Texture2DContent();
            //model.Texture.Mipmaps.Add(bc);
            //return model;

            SpAnimationInfo model = new SpAnimationInfo();
            List<SpAnimationFrame> listFrame = new List<SpAnimationFrame>();
            string[] tmp = input.Split(new string[] { "{|}" }, StringSplitOptions.None);
            string file = tmp[0];
            string path = System.IO.Path.GetDirectoryName(file);
            string fileName = System.IO.Path.GetFileNameWithoutExtension(file);
            string textureName = path + "\\" + fileName + "_texture.png";


            // Load the sprite texture into memory.
            ExternalReference<TextureContent> textureReference =
                        new ExternalReference<TextureContent>(textureName);

            TextureContent texture =
            context.BuildAndLoadAsset<TextureContent,
                                      TextureContent>(textureReference, "TextureProcessor");

            BitmapContent bc = texture.Faces[0][0];


            //throw new Exception(textureName);
            JsonData jData = LitJson.JsonMapper.ToObject(tmp[1]);
            JsonData frames = jData["frames"];
            for (int i = 0; i < frames.Count; i++)
            {
                JsonData jcur = frames[i];
                SpAnimationFrame frame = new SpAnimationFrame();
                frame.Name = jcur["name"].ToString();
                Vector2 tmpVector = Vector2.Zero;
                frame.Offset = new Vector2();
                tmpVector.X = float.Parse(jcur["offset"]["x"].ToString()) * bc.Width;
                tmpVector.Y = float.Parse(jcur["offset"]["y"].ToString()) * bc.Height;
                frame.Offset = tmpVector;
                frame.Size = new Vector2();
                tmpVector.X = float.Parse(jcur["size"]["x"].ToString()) * bc.Width;
                tmpVector.Y = float.Parse(jcur["size"]["y"].ToString()) * bc.Height;
                frame.Size = tmpVector;
                listFrame.Add(frame);
            }
            model.Frames = listFrame;
            frames = jData["animations"];
            frames = frames[0];
            model.IsLoop = Boolean.Parse(frames["loops"].ToString());
            model.Name = frames["name"].ToString();
            model.IsSmooth = Boolean.Parse(frames["smooth"].ToString());
            List<SpAnimationFrame> tmpList = new List<SpAnimationFrame>();
            frames = frames["key_frames"];
            for (int i = 0; i < frames.Count; i++)
            {
                JsonData jcur = frames[i];
                foreach (var item in model.Frames)
                {
                    if (jcur["frame"].ToString() == item.Name)
                    {
                        item.During = 1000 * float.Parse(jcur["duration"].ToString());
                        tmpList.Add(item);
                    }
                }
            }
            model.Frames = tmpList; 

            return model;
        }
    }
}
